package com.easywb.consulweb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulWebApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    private DiscoveryClient discoveryClient;


    @Autowired
    private RestTemplate rsestTemplate;
    @RequestMapping(value = "/sasas")
    public String t() {
        String serviceUrl = getServiceUrl("consul-user-center") + "/test";
        String result = rsestTemplate.getForObject(serviceUrl, String.class);

        return result;
    }
    public String getServiceUrl(String name) {
        List<ServiceInstance> list = discoveryClient.getInstances(name);
        if (list != null && !list.isEmpty()) {
            return list.get(0).getUri().toString();
        }
        return null;
    }
    public static void main(String[] args) {
        SpringApplication.run(ConsulWebApplication.class, args);
    }

}

